#!/bin/sh
#
# Author: Kees Bos <k.bos@zx.nl>
#

### BEGIN INIT INFO
# Provides:		fwmacro
# Required-Start:	$network $local_fs $syslog
# Required-Stop:	$network $local_fs $syslog
# Default-Start:	2 3 4 5
# Default-Stop:		0 1 6
# Short-Description:	Start fwmacro compiled iptables firewall rules
# Description:		Use the meta rules from fwmacro to
#			generate and use iptables firewall rules
### END INIT INFO

PATH=/sbin:/usr/sbin:/bin:/usr/bin
DESC="fwmacro firewall rules"
SCRIPTNAME=/etc/init.d/fwmacro
ETCDIR=/etc/fwmacro
IPv4RULES=$ETCDIR/ipv4.rules
IPv6RULES=$ETCDIR/ipv6.rules
IPv4STOPRULES=$ETCDIR/ipv4stop.rules
IPv6STOPRULES=$ETCDIR/ipv6stop.rules

# Exit if the fwmacro is not installed
[ -d /etc/fwmacro ] || exit 0
# Exit if iptables is not installed
[ -x /sbin/iptables ] || exit 0

# Arguments:
# start		start the service
# stop		stop the service
# restart	stop and restart the service if the service is already 
#		running, otherwise start the service
# try-restart	restart the service if the service is already running
# reload	cause the configuration of the service to be reloaded without 
#		actually stopping and restarting the service
# force-reload	cause the configuration to be reloaded if the service supports 
#		this, otherwise restart the service if it is running
# status	print the current status of the service

check_depenencies ( ) {
	[ -d /etc/fwmacro ] || exit 5
	# Exit if the fwmacro is not installed
	[ -d /etc/fwmacro ] || (echo "fwmacro is not installed" >&2 ; exit 5)
	# Exit if iptables is not installed
	[ -x /sbin/iptables ] || (echo "iptables is not installed" >&2 ; exit 5)
	# Exit if IPv4 stop rules are missing
	[ -f $IPv4STOPRULES ] || echo "File missing: $IPv4STOPRULES" >&2
	# Exit if IPv4 rules are missing
	[ -f $IPv4RULES ] || echo "File missing: $IPv4RULES" >&2
	if [ -x /sbin/ip6tables ] ; then
		# Exit if IPv6 stop rules are missing
		[ -f $IPv6STOPRULES ] || echo "File missing: $IPv6STOPRULES" >&2
		# Exit if IPv6 rules are missing
		[ -f $IPv6RULES ] || echo "File missing: $IPv6RULES" >&2
	fi
}

case "$1" in
	start|restart|reload|force-reload)
		check_depenencies
		iptables-restore $IPv4RULES
		if [ -x /sbin/ip6tables ] ; then
			ip6tables-restore $IPv6RULES
		fi
		;;
	stop)
		check_depenencies
		iptables-restore $IPv4STOPRULES
		if [ -x /sbin/ip6tables ] ; then
			ip6tables-restore $IPv6STOPRULES
		fi
		;;
	try-restart)
		check_depenencies
		;;
	status)
		iptables -L>/dev/null && exit 0 || exit $?
		;;
	*)
		echo "Usage: $0 {start|stop|restart|reload|force-reload|try-restart}" >&2
		exit 3
		;;
esac
exit 0
